function setItem(key, value) {
  return new Promise((resolve, reject) => {
    const data = {}
    data[key] = value
    chrome.storage.local.set(data, () => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError)
      } else {
        resolve()
      }
    })
  })
}

function getItem(key) {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(key, (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError)
      } else {
        resolve(result[key] || null)
      }
    })
  })
}

function getRandomIntInRange(_min, _max) {
  let min = parseInt(_min)
  let max = parseInt(_max)
  if (min > max) {
    throw new Error('min should be less than or equal to max')
  }
  return Math.floor(Math.random() * (max - min + 1)) + min
}

// 获取IP相关信息的封装方法
async function getIPInfo() {
  try {
    // 发送请求获取 IP 信息
    const response = await fetch(
      'https://check.myclientip.com/sys/config/ip/get-visitor-ip?type=ip2location',
      {
        headers: {
          accept:
            'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'accept-language': 'tr',
          'cache-control': 'max-age=0',
          priority: 'u=0, i',
          'sec-ch-ua': '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"Windows"',
          'sec-fetch-dest': 'document',
          'sec-fetch-mode': 'navigate',
          'sec-fetch-site': 'none',
          'sec-fetch-user': '?1',
          'upgrade-insecure-requests': '1',
        },
        referrerPolicy: 'strict-origin-when-cross-origin',
        body: null,
        method: 'GET',
        mode: 'cors',
        credentials: 'omit',
      },
    )

    // 判断是否响应成功
    if (!response.ok) {
      throw new Error('Failed to fetch IP info')
    }

    // 获取 JSON 数据
    const data = await response.json()

    // 返回获取到的IP相关信息
    return data
  } catch (error) {
    console.error('Error fetching IP information:', error)
    return null
  }
}


function randomSelectRadioBySelectors(...selectors) {
  return new Promise((resolve,reject) => {
  // 通过选择器获取所有单选按钮元素
  const radios = selectors.map(selector => document.querySelector(selector)).filter(Boolean);

  if (radios.length > 0) {
      // 随机选择一个单选按钮
      const randomIndex = Math.floor(Math.random() * radios.length);
      // 设置选中的单选按钮为选中状态
      radios[randomIndex].checked = true;
      // 触发单选按钮的change事件，以确保相关的事件监听器能够响应
      const event = new Event('change', { bubbles: true });
      radios[randomIndex].dispatchEvent(event);
      resolve(radios[randomIndex].value);
  } else {
      console.log('未找到任何单选按钮');
      reject('未找到任何单选按钮');
  }

});
}

function delay(ms=1000) {
  return new Promise(resolve => setTimeout(resolve, ms));
}


export { delay, setItem, getItem, getRandomIntInRange, getIPInfo, randomSelectRadioBySelectors }
